//首先定义一个栈，并写出栈的相关操作
typedef int STDataType;
typedef struct Stack
{
	STDataType* arr;
	int capacity; //栈的空间大小
	int top; //栈顶
}ST;

////////////////////////////////////////////////////
   void STInit(ST* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

//判断栈是否为空
bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

//入栈
void StackPush(ST* ps, STDataType x)
{
	assert(ps);

	//判断空间是否充足，不足增容
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->arr, newcapacity * sizeof(STDataType));
		if (tmp==NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
	//空间足够
	ps->arr[ps->top++] = x;
}

//出栈
void StackPop(ST* ps)
{
	assert(ps);
	//判断栈是否没有数据，是空栈
	//assert(ps->arr)
	assert(!StackEmpty(ps));

	--ps->top;
}

//取栈顶元素
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->arr[ps->top - 1];
}

//获取栈中有效元素个数
int STSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

//栈的销毁
void STDestroy(ST* ps)
{
	assert(ps);
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}
////////////////////////////////////////////////
bool isValid(char* s) 
{
    ST st;
    STInit(&st);
    
    //遍历字符串s
    char* ps=s;
    while(*ps!='\0')
    {
        //左括号入栈
        if(*ps=='(' || *ps=='[' || *ps=='{')
        {
            StackPush(&st,*ps);
        }
        else
        {
            //右括号，比较
            //为空（只有一个左括号）直接false
            if(StackEmpty(&st))
            {
                return false;
            }
           char a= StackTop(&st);
           if( (*ps==')' && a=='(')
           || (*ps==']' && a=='[')
           ||(*ps=='}' && a=='{') )
           {
             StackPop(&st);
           }
           else
           {
            STDestroy(&st);
            return false;
           }
        }
        ps++;
    }
    bool ret=StackEmpty(&st)==true;
    //销毁
    STDestroy(&st);
    return ret;
}
   